<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="工单ID" prop="workOrderId">
        <el-input
          v-model="queryParams.workOrderId"
          placeholder="请输入工单ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工序执行记录ID" prop="operationRecordId">
        <el-input
          v-model="queryParams.operationRecordId"
          placeholder="请输入工序执行记录ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备ID" prop="equipmentId">
        <el-input
          v-model="queryParams.equipmentId"
          placeholder="请输入设备ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="严重程度" prop="severity">
        <el-input
          v-model="queryParams.severity"
          placeholder="请输入严重程度"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上报人ID" prop="reportedBy">
        <el-input
          v-model="queryParams.reportedBy"
          placeholder="请输入上报人ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上报时间" prop="reportTime">
        <el-date-picker clearable
          v-model="queryParams.reportTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择上报时间">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['production-service:exception:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['production-service:exception:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['production-service:exception:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['production-service:exception:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="exceptionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="异常记录ID" align="center" prop="anomalyId" />
      <el-table-column label="工单ID" align="center" prop="workOrderId" />
      <el-table-column label="工序执行记录ID" align="center" prop="operationRecordId" />
      <el-table-column label="设备ID" align="center" prop="equipmentId" />
      <el-table-column label="异常类型" align="center" prop="anomalyType" />
      <el-table-column label="异常详细描述" align="center" prop="description" />
      <el-table-column label="严重程度" align="center" prop="severity" />
      <el-table-column label="上报人ID" align="center" prop="reportedBy" />
      <el-table-column label="上报时间" align="center" prop="reportTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.reportTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="处理状态" align="center" prop="status" />-->
<!--      <el-table-column label="处理人ID" align="center" prop="resolvedBy" />-->
<!--      <el-table-column label="解决时间" align="center" prop="resolvedTime" width="180">-->
<!--        <template #default="scope">-->
<!--          <span>{{ parseTime(scope.row.resolvedTime, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">-->
<!--        <template #default="scope">-->
<!--          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="最后更新时间" align="center" prop="updatedAt" width="180">-->
<!--        <template #default="scope">-->
<!--          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['production-service:exception:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['production-service:exception:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改生产异常记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="exceptionRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="工单ID" prop="workOrderId">
          <el-select
              v-model="form.workOrderId"
              placeholder="请选择工单"
              filterable
              clearable
              :loading="loadingWorkOrders"
          >
            <el-option
                v-for="item in workOrderOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工序执行记录ID" prop="operationRecordId">
          <el-select
              v-model="form.operationRecordId"
          placeholder="请选择记录ID"
          clearable
          filterable
          >
          <el-option
              v-for="item in recordOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
          </el-select>
        </el-form-item>
        <el-form-item label="设备ID" prop="equipmentId"   >
<!--          <el-input v-model="form.equipmentId" placeholder="请输入设备ID" />-->
          <el-select
              v-model="form.equipmentId"
              placeholder="请选择设备ID"
              clearable
              filterable
          >
            <el-option
                v-for="item in equipmentOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="异常类型" prop="anomalyType">
          <el-select v-model="form.anomalyType" placeholder="请选择异常类型">
            <el-option label="生产异常" value="生产异常" />
            <el-option label="设备异常" value="设备异常" />
          </el-select>
        </el-form-item>
        <el-form-item label="异常详细描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="严重程度" prop="severity">
          <el-input v-model="form.severity" placeholder="请输入严重程度" />
        </el-form-item>

<!--        <el-form-item label="上报人ID" prop="reportedBy">-->
<!--          <el-input v-model="form.reportedBy" placeholder="请输入上报人ID" />-->
<!--        </el-form-item>-->

<!--        <el-form-item label="任务状态" prop="status">-->
<!--            <el-select v-model="form.status" placeholder="请选择任务状态">-->
<!--                <el-option label="未完成" value="未完成"/>-->
<!--                <el-option label="已完成" value="已完成"/>-->
<!--            </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="上报时间" prop="reportTime">
          <el-date-picker clearable
            v-model="form.reportTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择上报时间">
          </el-date-picker>
        </el-form-item>
<!--        <el-form-item label="处理人ID" prop="resolvedBy">-->
<!--          <el-input v-model="form.resolvedBy" placeholder="请输入处理人ID" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="解决时间" prop="resolvedTime">-->
<!--          <el-date-picker clearable-->
<!--            v-model="form.resolvedTime"-->
<!--            type="date"-->
<!--            value-format="YYYY-MM-DD"-->
<!--            placeholder="请选择解决时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="创建时间" prop="createdAt">-->
<!--          <el-date-picker clearable-->
<!--            v-model="form.createdAt"-->
<!--            type="date"-->
<!--            value-format="YYYY-MM-DD"-->
<!--            placeholder="请选择创建时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="最后更新时间" prop="updatedAt">-->
<!--          <el-date-picker clearable-->
<!--            v-model="form.updatedAt"-->
<!--            type="date"-->
<!--            value-format="YYYY-MM-DD"-->
<!--            placeholder="请选择最后更新时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Exception">
import { listException, getException, delException, addException, updateException } from "@/api/production-service/exception.js"
import {listRecords} from "@/api/production-service/records.js";
import {listOrders} from "@/api/workorder-service/orders.js";
import { ref, onMounted } from 'vue';
//上报人ID
import useUserStore from "@/store/modules/user.js";
const userStore = useUserStore()


const recordOptions = ref([]);
const equipmentOptions= ref([])
// 查询新建记录中——工序执行记录ID的下拉框
const loadOptions = async () => {
  try {
    const res = await listRecords({
      pageSize: 1000 // 获取足够多的记录
    })

    // 转换数据：假设接口返回的字段是 recordId
    recordOptions.value = res.rows.map(item => ({
      value: item.recordId,  // 实际值对应 recordId
      label: `记录ID: ${item.recordId}` // 下拉显示文本
    }))
    console.log(recordOptions.value)

    // 如果需要显示更多信息（如工单号）：
    // label: `ID: ${item.recordId} (工单: ${item.workOrderId})`
    equipmentOptions.value = res.rows.map(item => ({
      value: item.equipmentId,  // 实际值对应 recordId
      label: `设备ID: ${item.equipmentId}` // 下拉显示文本
    }))
  } catch (error) {
    console.error('加载记录ID列表失败:', error)
  }
}
// 组件挂载时加载选项
onMounted(() => {
  loadOptions()
})
//查询工单id
const workOrderOptions = ref([]) // 存储下拉框选项
const loadingWorkOrders = ref(false) // 加载状态
// 获取工单列表数据
const fetchWorkOrders = async () => {
  loadingWorkOrders.value = true
  try {
    const res = await listOrders({
      pageSize: 1000 // 获取足够多的记录
    })

    // 转换数据格式，确保包含 id 和 productName 字段
    workOrderOptions.value = res.rows.map(item => ({
      value: item.id, // 实际存储的值是工单ID
      label: `${item.id} - ${item.productName}` // 下拉框显示的内容
    }))
  } catch (error) {
    console.error('获取工单列表失败:', error)
  } finally {
    loadingWorkOrders.value = false
  }
}

// 组件挂载时加载数据
onMounted(() => {
  fetchWorkOrders()
})


const { proxy } = getCurrentInstance()

const exceptionList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    workOrderId: null,
    operationRecordId: null,
    equipmentId: null,
    anomalyType: null,
    description: null,
    severity: null,
    reportedBy: null,
    reportTime: null,
    status: "未完成",
    resolution: null,
    resolvedBy: null,
    resolvedTime: null,
    createdAt: null,
    updatedAt: null
  },
  rules: {
    anomalyType: [
      { required: true, message: "异常类型不能为空", trigger: "change" }
    ],
    description: [
      { required: true, message: "异常详细描述不能为空", trigger: "blur" }
    ],
    reportTime: [
      { required: true, message: "上报时间不能为空", trigger: "blur" }
    ],
    // createdAt: [
    //   { required: true, message: "创建时间不能为空", trigger: "blur" }
    // ],
    // updatedAt: [
    //   { required: true, message: "最后更新时间不能为空", trigger: "blur" }
    // ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询生产异常记录列表 */
function getList() {
  loading.value = true
  listException(queryParams.value).then(response => {
    exceptionList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    anomalyId: null,
    workOrderId: null,
    operationRecordId: null,
    equipmentId: null,
    anomalyType: null,
    description: null,
    severity: null,
    reportedBy: null,
    reportTime: null,
    status: "未完成",
    resolution: null,
    resolvedBy: null,
    resolvedTime: null,
    createdAt: null,
    updatedAt: null
  }
  proxy.resetForm("exceptionRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.anomalyId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加生产异常记录"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _anomalyId = row.anomalyId || ids.value
  getException(_anomalyId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改生产异常记录"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["exceptionRef"].validate(valid => {
    if (valid) {
      form.value.reportedBy=userStore.name
      if (form.value.anomalyId != null) {
        updateException(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addException(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _anomalyIds = row.anomalyId || ids.value
  proxy.$modal.confirm('是否确认删除生产异常记录编号为"' + _anomalyIds + '"的数据项？').then(function() {
    return delException(_anomalyIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('production-service/exception/export', {
    ...queryParams.value
  }, `exception_${new Date().getTime()}.xlsx`)
}

getList()
</script>
